package com.cw.paging3

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.cw.paging3.databinding.ListItemBinding

/**
 * 更新MainListAdapter，让其继承PagingDataAdapter，PagingDataAdapter将Data与ViewHolder进行绑定
 * Paging接收一个DiffUtil的Callback处理Item的diff，这里定一个DataDifferntiator，用于PagingDataAdapter的构造。
 */
class MainListAdapter : PagingDataAdapter<Data, MainListAdapter.DataViewHolder>(COMPARATOR) {

    override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
        holder.binding.textViewName.text =
            "${getItem(position)?.first_name} ${getItem(position)?.last_name}"
        holder.binding.textViewEmail.text = getItem(position)?.email
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder {
        return DataViewHolder(
            ListItemBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    class DataViewHolder(var binding: ListItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
    }

    /**
     * Paging接收一个DiffUtil的Callback处理Item的diff，这里定一个DataDifferntiator，用于PagingDataAdapter的构造。
     */
    companion object {
        private val COMPARATOR = object : DiffUtil.ItemCallback<Data>() {
            override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
                return oldItem == newItem
            }
        }
    }
//    object DataComparator : DiffUtil.ItemCallback<Data>() {
//
//        override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {
//            return oldItem.id == newItem.id
//        }
//
//        override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
//            return oldItem == newItem
//        }
//    }

}
